package com.zhu.tool_test.starke.util.buffer.core;


import com.zhu.tool_test.starke.util.buffer.StarkeProcess;

import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 4everlynn
 * @version V1.0
 * @description 拼接字符串
 * @date 2019-03-12
 */
public class StarkeBuilder {

    @SuppressWarnings("RegExpRedundantEscape")
    private static Pattern index = Pattern.compile("\\{\\}");

    /**
     * 让字符串拼接支持Log4J风格
     *
     * @param format 格式
     * @param values 占位符的数据
     * @return 拼接完成的字符串
     */
    public static String build(String format, Object... values) {
        Deque<Object> queue = new ArrayDeque<>(Arrays.asList(values));
        Matcher matcher = index.matcher(format);
        while (matcher.find()) {
            if (queue.peek() != null) {
                String string = queue.pop().toString();
                string = string.replaceAll("\\$", "<temporary>");
                format = format.replaceFirst(index.pattern(), string);
            }
        }
        format = format.replaceAll("<temporary>", "\\$");
        return format;
    }

    public static <T> String buildString(List<T> targetList, StarkeProcess<T> process) {
        StringBuilder builder = new StringBuilder();
        for (T target : targetList) {
            String string = "";
            if (process != null) {
                string = process.buildString(target);
            }
            builder.append(string)
                    .append(",");
        }
        return builder.toString().replaceAll(",$", "");
    }
}
